package cn.view;

/*
  @ClassName EmployeeSQView//Employee Statistical queries view员工信息统计查询类缩写
 */
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.EmployeeDao;
import cn.entity.Employee;

public class EmployeeSQView extends JInternalFrame {
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;
    JTextField searchField;

    public EmployeeSQView() {
        super("员工统计查询界面", false, true, false, true);
        initializeComponents();
        this.setSize(700, 500);
        this.setVisible(true);
    }

    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        EmployeeDao dao = new EmployeeDao();
        List<Object[]> ls = dao.selectAll();
        String[] title = { "员工编号", "员工姓名", "员工密码", "级别", "员工电话", "员工工资", "备注" };
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{80, 90, 90,50, 90, 80, 140});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for (int i = 0; i < detail.getColumnCount(); i++) {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }

        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }


    private List<Employee> convertToEmployeeList(List<Object[]> data) {
        List<Employee> employees = new ArrayList<>();
        for (Object[] row : data) {
            Employee emp = new Employee();
            emp.setEid((String) row[0]);
            emp.setEname((String) row[1]);
            emp.setEpw((String) row[2]);
            emp.setElevel((String) row[3]);
            emp.setEPhone((String) row[4]);
            emp.setSalary((String) row[5]);
            emp.setNotes((String) row[6]);
            employees.add(emp);
        }
        return employees;
    }


    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton searchButton = new JButton("搜索员工");
        searchButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showSearchEmployeeDialog();
            }
        });

        JButton exportButton = new JButton("导出员工信息");
        exportButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportEmployeeDialog();
            }
        });

        JButton queryPurchaseButton = new JButton("查询员工采购量");
        queryPurchaseButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryPurchaseDialog();
            }
        });

        Jbutton.add(searchButton);
        Jbutton.add(exportButton);
        Jbutton.add(queryPurchaseButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }

    private void showSearchEmployeeDialog() {
        JTextField searchField = new JTextField(20);
        JPanel panel = new JPanel();
        panel.add(new JLabel("请输入员工姓名或ID:"));
        panel.add(searchField);

        int result = JOptionPane.showConfirmDialog(null, panel, "搜索员工", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String keyword = searchField.getText();
            EmployeeDao dao = new EmployeeDao();
            List<Employee> employees = dao.queryEmployeesByKeyword(keyword);
            if (employees.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合条件的员工信息");
            } else {
                model.setRowCount(0);
                for (Employee emp : employees) {
                    model.addRow(new Object[]{
                            emp.getEid(),
                            emp.getEname(),
                            emp.getEpw(),
                            emp.getElevel(),
                            emp.getEPhone(),
                            emp.getSalary(),
                            emp.getNotes()
                    });
                }
            }
        }
    }

    private void showExportEmployeeDialog() {
        // 获取列名
        int columnCount = model.getColumnCount();
        Object[] columnIdentifiers = new Object[columnCount];
        for (int i = 0; i < columnCount; i++) {
            columnIdentifiers[i] = model.getColumnName(i);
        }

        // 获取数据
        int rowCount = model.getRowCount();
        List<Object[]> dataVector = new ArrayList<>();
        for (int i = 0; i < rowCount; i++) {
            Object[] rowData = new Object[columnCount];
            for (int j = 0; j < columnCount; j++) {
                rowData[j] = model.getValueAt(i, j);
            }
            dataVector.add(rowData);
        }

        // 创建 CSV 文件
        File csvFile = CSVUtil.createCSVFile(columnIdentifiers, dataVector, "output/path", "员工数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "员工数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出员工数据失败");
        }
    }




    private void showQueryPurchaseDialog() {
        EmployeeDao dao = new EmployeeDao();
        List<Object[]> purchaseData = dao.queryEmployeePayData();
        String[] columnNames = { "员工编号", "员工姓名", "商品种类数", "采购总数量", "采购总价" };
        DefaultTableModel purchaseModel = new DefaultTableModel(purchaseData.toArray(new Object[][]{}), columnNames);

        JTable purchaseTable = new JTable(purchaseModel);
        JScrollPane scrollPane = new JScrollPane(purchaseTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        JDialog dialog = new JDialog((Frame) null, "员工采购统计", true);
        dialog.getContentPane().add(scrollPane);
        dialog.setSize(600, 400);
        dialog.setVisible(true);
    }
}
